<template>
  <el-container class="common-layout">
    <!-- 顶部 Header -->
    <el-header class="header">
      <span>后台管理系统</span>
      <span style="margin-left: auto; color: #fff;">
        当前用户：{{ mockUserDisplay.username }} | 角色：{{ mockUserDisplay.roles.join(', ') }}
      </span>
      <!-- 语言切换 -->
      <el-select
        v-model="currentLang"
        size="small"
        style="margin-left: 16px; width: 100px;"
        @change="switchLanguage"
      >
        <el-option label="中文" value="zh_CN" />
        <el-option label="English" value="en_US" />
      </el-select>
    </el-header>

    <el-container>
      <!-- 左侧菜单 -->
      <el-aside width="200px" style="background-color: #fff; border-right: 1px solid #eee;">
        <el-menu
          :default-active="activeTab"
          class="side-menu"
          @select="handleMenuSelect"
          background-color="#fff"
          text-color="#333"
          active-text-color="#409eff"
        >
          <el-menu-item index="user">
            <el-icon><User /></el-icon>
            <span>{{ t('user_management') }}</span>
          </el-menu-item>
          <el-menu-item v-if="isAdmin" index="role">
            <el-icon><Star /></el-icon>
            <span>{{ t('role_management') }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-main class="content-area">
        <!-- 用户管理 -->
        <div v-if="activeTab === 'user'" class="user-management">
          <div class="search-bar">
            <el-input
              v-model="searchKeyword"
              :placeholder="t('input_search')"
              clearable
              size="small"
              style="width: 300px; margin-right: 16px;"
              @input="handleSearch"
            />
            <el-button
              v-if="isAdmin"
              type="primary"
              size="small"
              @click="addUser"
            >
              {{ t('add_user') }}
            </el-button>
          </div>

          <el-table
            :data="paginatedUsers"
            style="width: 100%"
            border
            stripe
            :default-sort="{ prop: 'id', order: 'ascending' }"
            @sort-change="handleSortChange"
            v-loading="loading"
          >
            <el-table-column prop="id" :label="t('id')" width="80" sortable />
            <el-table-column prop="username" :label="t('username')" sortable />
            <el-table-column prop="enName" :label="t('english_name')" />
            <el-table-column prop="mobile" :label="t('phone')" />
            <el-table-column prop="email" :label="t('email')" />
            <el-table-column prop="birthday" :label="t('birthday')" :formatter="formatDateColumn" />
            <el-table-column prop="isActive" :label="t('status')" width="100">
              <template #default="{ row }">
                <el-tag :type="row.isActive ? 'success' : 'danger'">
                  {{ row.isActive ? t('enabled') : t('disabled') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createtime" :label="t('created_at')" sortable :formatter="formatDateTimeColumn" />
            <el-table-column :label="t('actions')" width="220">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="showUserDetail(row)">{{ t('details') }}</el-button>
                <el-button
                  v-if="canEditUser(row)"
                  type="text"
                  size="small"
                  @click="editUser(row)"
                >
                  {{ t('edit') }}
                </el-button>
                <el-button
                  v-if="isAdmin"
                  type="text"
                  size="small"
                  style="color: #f56c6c"
                  @click="deleteUser(row.id)"
                >
                  {{ t('delete') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="filteredUsers.length"
              layout="total, prev, pager, next, sizes"
              :page-sizes="[20, 50, 100]"
              @size-change="handlePageSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="dialogVisible" :title="t('user_details')" width="40%">
      <el-descriptions :column="1" border size="small">
        <el-descriptions-item :label="t('id')">{{ selectedUser.id }}</el-descriptions-item>
        <el-descriptions-item :label="t('username')">{{ selectedUser.username }}</el-descriptions-item>
        <el-descriptions-item :label="t('english_name')">{{ selectedUser.enName }}</el-descriptions-item>
        <el-descriptions-item :label="t('phone')">{{ selectedUser.mobile }}</el-descriptions-item>
        <el-descriptions-item :label="t('email')">{{ selectedUser.email }}</el-descriptions-item>
        <el-descriptions-item :label="t('birthday')">{{ formatDate(selectedUser.birthday) }}</el-descriptions-item>
        <el-descriptions-item :label="t('status')">{{ selectedUser.isActive ? t('enabled') : t('disabled') }}</el-descriptions-item>
        <el-descriptions-item :label="t('created_at')">{{ formatDate(selectedUser.createtime) }}</el-descriptions-item>
        <el-descriptions-item :label="t('updated_at')">{{ formatDate(selectedUser.updatetime) }}</el-descriptions-item>
        <el-descriptions-item :label="t('roles')">
          {{ getUserRoleNames(selectedUser.id).join(', ') || t('no_roles') }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" :title="t('edit_user')" width="500px" @close="resetEditForm">
      <el-form ref="editFormRef" :model="editForm" label-width="100px" size="small">
        <el-form-item :label="t('username')">
          <el-input v-model="editForm.userName" />
        </el-form-item>
        <el-form-item :label="t('english_name')">
          <el-input v-model="editForm.enname" />
        </el-form-item>
        <el-form-item :label="t('phone')">
          <el-input v-model="editForm.mobile" />
        </el-form-item>
        <el-form-item :label="t('email')">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item :label="t('birthday')">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            :placeholder="t('select_birthday')"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="t('status')">
          <el-switch v-model="editForm.isActive" :active-text="t('enabled')" :inactive-text="t('disabled')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="submitEdit" :loading="editLoading">{{ t('save') }}</el-button>
      </template>
    </el-dialog>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="addDialogVisible" :title="t('add_user')" width="500px" @close="resetAddForm">
      <el-form ref="addFormRef" :model="addForm" label-width="100px" size="small">
        <el-form-item :label="t('username')">
          <el-input v-model="addForm.userName" />
        </el-form-item>
        <el-form-item :label="t('english_name')">
          <el-input v-model="addForm.enname" />
        </el-form-item>
        <el-form-item :label="t('phone')">
          <el-input v-model="addForm.mobile" />
        </el-form-item>
        <el-form-item :label="t('email')">
          <el-input v-model="addForm.email" />
        </el-form-item>
        <el-form-item :label="t('password')">
          <el-input v-model="addForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item :label="t('birthday')">
          <el-date-picker
            v-model="addForm.birthday"
            type="date"
            :placeholder="t('select_birthday')"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="t('status')">
          <el-switch v-model="addForm.isActive" :active-text="t('enabled')" :inactive-text="t('disabled')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="submitAdd" :loading="addLoading">{{ t('create') }}</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { User, Star } from '@element-plus/icons-vue'

const formatDateToInput = (isoStr: string | null): string | null => {
  if (!isoStr) return null
  return isoStr.substring(0, 10) // 输出 "2000-10-09"
}

interface CurrentUser {
  user_id: number
  username: string
  role_id: number
  role_name: string
}

const router = useRouter()

// --- 多语言配置 ---
type LanguageCode = 'zh_CN' | 'en_US'
const currentLang = ref<LanguageCode>('zh_CN')

// 默认翻译表
const langPack = {
  zh_CN: {
    app_title: '后台管理系统',
    user_management: '用户管理',
    role_management: '角色管理',
    input_search: '输入用户ID/用户名/邮箱等',
    add_user: '新增用户',
    id: 'ID',
    username: '用户名',
    english_name: '英文名',
    phone: '手机号',
    email: '邮箱',
    birthday: '生日',
    status: '状态',
    enabled: '启用',
    disabled: '禁用',
    created_at: '创建时间',
    updated_at: '更新时间',
    actions: '操作',
    details: '详情',
    edit: '修改',
    delete: '删除',
    user_details: '用户详情',
    roles: '角色',
    no_roles: '无',
    cancel: '取消',
    save: '保存',
    create: '创建',
    select_birthday: '选择生日',
    password: '密码',
    current_user: '当前用户',
    role: '角色',
    load_failed: '加载失败',
    update_success: '更新成功',
    update_failed: '更新失败',
    confirm_delete: '确认删除该用户？',
    prompt: '提示',
    delete_success: '删除成功',
    delete_failed: '删除失败',
    create_success: '创建成功',
    create_failed: '创建失败',
    no_permission: '您没有权限执行此操作',
    edit_user: '编辑用户'
  },
  en_US: {
    app_title: 'Admin System',
    user_management: 'User Management',
    role_management: 'Role Management',
    input_search: 'Search by ID, username or email',
    add_user: 'Add User',
    id: 'ID',
    username: 'Username',
    english_name: 'English Name',
    phone: 'Phone',
    email: 'Email',
    birthday: 'Birthday',
    status: 'Status',
    enabled: 'Enabled',
    disabled: 'Disabled',
    created_at: 'Created At',
    updated_at: 'Updated At',
    actions: 'Actions',
    details: 'Details',
    edit: 'Edit',
    delete: 'Delete',
    user_details: 'User Details',
    roles: 'Roles',
    no_roles: 'None',
    cancel: 'Cancel',
    save: 'Save',
    create: 'Create',
    select_birthday: 'Select Birthday',
    password: 'Password',
    current_user: 'Current User',
    role: 'Role',
    load_failed: 'Load Failed',
    update_success: 'Update Success',
    update_failed: 'Update Failed',
    confirm_delete: 'Confirm to delete this user?',
    prompt: 'Prompt',
    delete_success: 'Delete Success',
    delete_failed: 'Delete Failed',
    create_success: 'Create Success',
    create_failed: 'Create Failed',
    no_permission: 'You do not have permission to perform this operation',
    edit_user: 'Edit User'
  }
}

// 翻译函数
const t = (key: keyof typeof langPack.zh_CN): string => {
  return langPack[currentLang.value][key] || key
}

// 切换语言
const switchLanguage = (): void => {
  localStorage.setItem('preferred_language', currentLang.value)
  ElMessage.success(currentLang.value === 'zh_CN' ? '语言已切换为中文' : 'Language switched to English')
}

// 当前登录用户（模拟）
const getCurrentUser = (): CurrentUser | null => {
  const data = localStorage.getItem('currentUser')
  if (data) {
    try {
      return JSON.parse(data)
    } catch (e) {
      console.error('解析 currentUser 失败', e)
      return null
    }
  }
  return null
}

const currentUser = getCurrentUser()
if (!currentUser) {
  router.push('/login')
}

const mockUser = currentUser!
const ROLE = { ADMIN: 1, VIP: 2, COMMON: 3 }
const isAdmin = computed(() => mockUser.role_id === ROLE.ADMIN)

const mockUserDisplay = computed(() => ({
  username: mockUser.username,
  roles: [mockUser.role_name]
}))

const activeTab = ref<'user' | 'role'>('user')
const handleMenuSelect = (index: string) => {
  if (index === 'role') {
    router.push('/roles')
  } else {
    activeTab.value = index as 'user'
  }
}

// 用户数据
const allUsers = ref<any[]>([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const sortProp = ref<string | null>(null)
const sortOrder = ref<'ascending' | 'descending' | null>(null)
const loading = ref(false)

const roles = ref<any[]>([
  { id: 1, name: '管理员', description: '系统最高权限' },
  { id: 2, name: 'VIP会员', description: '可修改自己信息' },
  { id: 3, name: '普通用户', description: '只能查看部分数据' }
])

const loadUsers = async () => {
  loading.value = true
  try {
    const res = await axios.get('/api/users')
    allUsers.value = res.data.data || []
  } catch {
    ElMessage.error(t('load_failed'))
    allUsers.value = []
  } finally {
    loading.value = false
  }
}

const visibleUsers = computed(() => {
  if (mockUser.role_id === ROLE.COMMON) return allUsers.value.slice(0, 3)
  return allUsers.value
})

const filteredUsers = computed(() => {
  const kw = searchKeyword.value.toLowerCase().trim()
  if (!kw) return visibleUsers.value
  return visibleUsers.value.filter(u =>
    String(u.id).includes(kw) ||
    (u.username && u.username.toLowerCase().includes(kw)) ||
    (u.email && u.email.toLowerCase().includes(kw))
  )
})

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredUsers.value.slice(start, start + pageSize.value)
})

const canEditUser = (user: any) => {
  if (mockUser.role_id === ROLE.ADMIN) return true
  if (mockUser.role_id === ROLE.VIP) return user.id === mockUser.user_id
  return false
}

const handleSearch = () => (currentPage.value = 1)
const handlePageChange = (page: number) => (currentPage.value = page)
const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}
const handleSortChange = (sortInfo: { prop: string | null; order: 'ascending' | 'descending' | null }) => {
  sortProp.value = sortInfo.prop
  sortOrder.value = sortInfo.order
}

const formatDate = (d: string | null) => (d ? new Date(d).toLocaleString('zh-CN') : '—')
const formatDateColumn = (r: any, c: any, v: any) => formatDate(v)
const formatDateTimeColumn = (r: any, c: any, v: any) => formatDate(v)

const dialogVisible = ref(false)
const selectedUser = ref<any>(null)
const showUserDetail = (user: any) => {
  selectedUser.value = user
  dialogVisible.value = true
}

// 编辑用户
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive<any>({
  id: null,
  userName: '',
  enname: '',
  mobile: '',
  email: '',
  birthday: '',
  isActive: true,
})
const editLoading = ref(false)
const editUser = (user: any) => {
  if (!canEditUser(user)) return ElMessage.warning(t('no_permission'))
  editForm.id = user.id
  editForm.userName = user.username || ''
  editForm.enname = user.enName || ''
  editForm.mobile = user.mobile || ''
  editForm.email = user.email || ''
  editForm.birthday = formatDateToInput(user.birthday)
  editForm.isActive = user.isActive ?? true
  editDialogVisible.value = true
}
const submitEdit = async () => {
  editLoading.value = true
  try {
    await axios.patch(`/api/users/${editForm.id}`, editForm)
    ElMessage.success(t('update_success'))
    editDialogVisible.value = false
    loadUsers()
  } catch {
    ElMessage.error(t('update_failed'))
  } finally {
    editLoading.value = false
  }
}
const resetEditForm = () => {
  Object.assign(editForm, {
    id: null,
    userName: '',
    enname: '',
    mobile: '',
    email: '',
    birthday: '',
    isActive: true,
  })
}

// 删除用户
const deleteUser = async (id: number) => {
  if (!isAdmin.value) return ElMessage.warning(t('no_permission'))
  try {
    await ElMessageBox.confirm(t('confirm_delete'), t('prompt'), { type: 'warning' })
    await axios.delete(`/api/users/${id}`)
    ElMessage.success(t('delete_success'))
    loadUsers()
  } catch {}
}

// 新增用户
const addDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = reactive<any>({
  userName: '',
  enname: '',
  mobile: '',
  email: '',
  password: '',
  birthday: '',
  isActive: true,
  roleIds: [] as number[],
})
const addLoading = ref(false)
const addUser = () => {
  Object.assign(addForm, {
    userName: '',
    enname: '',
    mobile: '',
    email: '',
    password: '',
    birthday: '',
    isActive: true,
    roleIds: [],
  })
  addDialogVisible.value = true
}
const submitAdd = async () => {
  addLoading.value = true
  try {
    await axios.post('/api/user', addForm)
    ElMessage.success(t('create_success'))
    addDialogVisible.value = false
    loadUsers()
  } catch {
    ElMessage.error(t('create_failed'))
  } finally {
    addLoading.value = false
  }
}
const resetAddForm = () => {
  Object.assign(addForm, {
    userName: '',
    enname: '',
    mobile: '',
    email: '',
    password: '',
    birthday: '',
    isActive: true,
    roleIds: [],
  })
}

const getUserRoleNames = (userId: number) => {
  const user = allUsers.value.find(u => u.id === userId)
  return user?.roles?.map((rid: number) => roles.value.find(r => r.id === rid)?.name).filter(Boolean) || []
}

// 初始化语言设置
onMounted(() => {
  const saved = localStorage.getItem('preferred_language')
  if (saved && (saved === 'zh_CN' || saved === 'en_US')) {
    currentLang.value = saved as LanguageCode
  }
  loadUsers()
})
</script>

<style scoped>
.el-table th {
  text-align: center;
}
.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.header {
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
}
.content-area {
  padding: 20px;
  background-color: #f5f7fa;
}
.search-bar {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>